package com.lyshop.guiyingshanding.fragments;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.lyshop.guiyingshanding.R;
import com.lyshop.guiyingshanding.activitys.MainActivity;
import com.lyshop.guiyingshanding.activitys.TicketActivity;
import com.lyshop.guiyingshanding.adapters.OrderRVAdapter;
import com.lyshop.guiyingshanding.adapters.OrderRecordRVAdapter;
import com.lyshop.guiyingshanding.base.BaseActivity;
import com.lyshop.guiyingshanding.base.BaseFragment;
import com.lyshop.guiyingshanding.bean.OrderInfoBean;
import com.lyshop.guiyingshanding.bean.OrderInfoGroupBean;
import com.lyshop.guiyingshanding.bean.UserInfoBean;
import com.lyshop.guiyingshanding.eventbus.EventCenter;
import com.lyshop.guiyingshanding.eventbus.EventConstants;
import com.lyshop.guiyingshanding.net.ActionCallbackListener;
import com.lyshop.guiyingshanding.utils.DataUtils;
import com.lyshop.guiyingshanding.utils.RouteUtil;
import com.lyshop.guiyingshanding.utils.ToastUtil;
import com.lyshop.guiyingshanding.utils.ToolbarUtils;
import com.lyshop.guiyingshanding.view.OrderSellDialog;
import com.lyshop.guiyingshanding.view.OrderUpdateDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zc.mychart.model.GoodsAllBean;
import com.zc.mychart.utils.ArithUtil;
import com.zc.mychart.utils.FormatUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class OrderFragment extends BaseFragment implements RadioGroup.OnCheckedChangeListener, View.OnClickListener, OrderRVAdapter.OrderListener, OrderRecordRVAdapter.RecordListener {
    private TextView tv_float_money;
    private TextView tv_recharge;
    private TextView tv_frozen_balance;
    private TextView tv_account_balance;
    private RelativeLayout rl_ticket;
    private TextView tv_ticket;
    private TextView tv_ticket02;
    private ImageView iv_ticket_un_use, iv_refresh_money;
    private ImageView iv_order_advert;
    private RadioGroup rg_tab_order;
    private SmartRefreshLayout refresh_layout;
    private TextView tv_go_trade;
    private RecyclerView rv_list;
    private TextView tv_empty;
    private int mPageIndex = 1;
    public static final int TYPE_INDEX_ORDER = 0;
    public static final int TYPE_INDEX_RECORD = 1;
    private OrderRVAdapter mOrderAdapter;
    private OrderRecordRVAdapter mRecordRVAdapter;
    private int mCurrentIndex = 0;//当前下标
    private View tool_bar;
    private List<OrderInfoBean> mSellOrderList;
    private List<OrderInfoGroupBean> mOrderInfoGroupList;
    private double orderMoney = 0;
    private double totalFloatMoney = 0;
    private OrderSellDialog mSellDialog;
    private String mCurrentOrderSellId = "";
    private OrderUpdateDialog mUpdateDialog;
    private ObjectAnimator rotateAnimator;


    @Override
    protected void initVariable() {
        ToolbarUtils.setToolbarHeight(mContext, tool_bar);
        mSellOrderList = new ArrayList<>();
        mOrderInfoGroupList = new ArrayList<>();
        mOrderAdapter = new OrderRVAdapter(getContext(), mOrderInfoGroupList);
        mRecordRVAdapter = new OrderRecordRVAdapter(getContext(), mSellOrderList);
        mOrderAdapter.setOrderListener(this);
        mRecordRVAdapter.setRecordListener(this);
        rv_list.setLayoutManager(new LinearLayoutManager(mContext));
        rv_list.setAdapter(mOrderAdapter);
        ((SimpleItemAnimator) rv_list.getItemAnimator()).setSupportsChangeAnimations(false);
    }

    @Override
    protected int setContentView() {
        return R.layout.fragment_order;
    }

    @Override
    protected void findViews(View rootView) {
        tool_bar = rootView.findViewById(R.id.v_toolbar);
        tv_float_money = rootView.findViewById(R.id.tv_float_money);
        tv_recharge = rootView.findViewById(R.id.tv_recharge);
        tv_frozen_balance = rootView.findViewById(R.id.tv_frozen_balance);
        tv_account_balance = rootView.findViewById(R.id.tv_account_balance);
        rl_ticket = rootView.findViewById(R.id.rl_ticket);
        tv_ticket = rootView.findViewById(R.id.tv_ticket);
        tv_ticket02 = rootView.findViewById(R.id.tv_ticket02);
        iv_ticket_un_use = rootView.findViewById(R.id.iv_ticket_un_use);
        iv_order_advert = rootView.findViewById(R.id.iv_order_advert);
        rg_tab_order = rootView.findViewById(R.id.rg_tab_order);
        refresh_layout = rootView.findViewById(R.id.refresh_layout);
        tv_go_trade = rootView.findViewById(R.id.tv_go_trade);
        rv_list = rootView.findViewById(R.id.rv_list);
        tv_empty = rootView.findViewById(R.id.tv_empty);
        iv_refresh_money = rootView.findViewById(R.id.iv_refresh_money);
        // 初始化属性动画：旋转两圈（720度）
        rotateAnimator = ObjectAnimator.ofFloat(iv_refresh_money, "rotation", 0f, 720f);
        rotateAnimator.setDuration(2000); // 总时长2秒（每圈1秒）
        rotateAnimator.setInterpolator(new LinearInterpolator()); // 匀速旋转
        rotateAnimator.setRepeatCount(0); // 不重复（直接转两圈）
    }

    @Override
    protected void setListeners() {
        tv_recharge.setOnClickListener(this);
        rg_tab_order.setOnCheckedChangeListener(this);
        iv_order_advert.setOnClickListener(this);
        rl_ticket.setOnClickListener(this);
        tv_go_trade.setOnClickListener(this);
        iv_refresh_money.setOnClickListener(this);
        refresh_layout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPageIndex = 1;
                getListDate();
                getAccount();
            }
        });

        refresh_layout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPageIndex++;
                getListDate();
            }
        });

        // 动画结束监听
        rotateAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                myApplication.updateUserDetail(); // 动画结束后刷新余额
            }
        });
    }

    @Override
    protected void refreshDataSource() {
        if (DataUtils.isLogin(mContext)) {
            //一到页面刷新
            getAccount();
            mPageIndex = 1;
            switch (mCurrentIndex) {
                case 0:
                    getNoManualOrderList();
                    break;
                case 1:
                    getTradeRecordList();
                    break;
            }
            //新手刚下单成功，弹去充值弹窗
            if (DataUtils.getGuideBuy(mContext)) {
                ((MainActivity) baseActivity).showGuideRechargeDialog();
            }
            if (mOrderAdapter != null){
                mOrderAdapter.notifyDataSetChanged();
            }
        } else {
            mOrderAdapter.clear();
            onLogoutStatus();
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        this.mPageIndex = 1;
        tv_go_trade.setVisibility(View.GONE);
        switch (checkedId) {
            case R.id.rb_order_list:
                rv_list.setAdapter(mOrderAdapter);
                mCurrentIndex = TYPE_INDEX_ORDER;
                getNoManualOrderList();
                break;
            case R.id.rb_record:
                rv_list.setAdapter(mRecordRVAdapter);
                mCurrentIndex = TYPE_INDEX_RECORD;
                getTradeRecordList();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_recharge:
                RouteUtil.toRechargeActivity((BaseActivity) mContext);
                break;
            case R.id.iv_order_advert:

                break;
            case R.id.rl_ticket:
                gotoActivity(mContext, TicketActivity.class, null);
                break;
            case R.id.tv_go_trade:
                List<GoodsAllBean> allList = myApplication.getAllList();
                if (null != allList && allList.size() > 0) {
                    RouteUtil.toMarketActivity(baseActivity,  allList.get(0).pro_code);
                } else {
                    ToastUtil.showToast(mContext, "暂未获取商品信息");
                }
                break;
            case R.id.iv_refresh_money:
                if (!rotateAnimator.isRunning()) {
                    rotateAnimator.start(); // 开始动画
                }
                break;
        }
    }

    public void getListDate() {
        switch (mCurrentIndex) {
            case TYPE_INDEX_ORDER:
                getNoManualOrderList();
                break;
            case TYPE_INDEX_RECORD:
                getTradeRecordList();
                break;
        }
    }

    /**
     * 获取用户信息
     */
    private void getAccount() {
        UserInfoBean userInfo = DataUtils.getUserInfo(mContext);
        if (userInfo == null) return;
        tv_account_balance.setText(FormatUtil.formatMoney(Double.valueOf(userInfo.availablebalance)) + "元");
        if (userInfo.not_use_ticket_count > 0) {
            rl_ticket.setVisibility(View.VISIBLE);
            iv_ticket_un_use.setVisibility(View.VISIBLE);
            tv_ticket.setText(userInfo.pro_ticket_money_sum + "元");
            tv_ticket02.setText("代金券待使用(" + userInfo.not_use_ticket_count + "张)");
        }else {
            rl_ticket.setVisibility(View.GONE);
        }
    }

    /**
     * 获取持有订单
     */
    private void getNoManualOrderList() {
        mAppAction.getHoldOrderList(new ActionCallbackListener<List<OrderInfoBean>>() {
            @Override
            public void onSuccess(List<OrderInfoBean> data) {
                refresh_layout.finishRefresh(1000);
                refresh_layout.setEnableLoadMore(false);
                if (data.size() > 0) {
                    updateOrderList(generateOrderGroupList(data), true);
                    tv_empty.setVisibility(View.GONE);
                    tv_go_trade.setVisibility(View.GONE);
                    rv_list.setVisibility(View.VISIBLE);
                } else {
                    tv_frozen_balance.setText("--");
                    tv_float_money.setText("--");
                    tv_float_money.setTextColor(ContextCompat.getColor(mContext, R.color.color_black_01));
                    mOrderAdapter.clear();
                    showEmptyView();
                }
                setOrderMoney();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                refresh_layout.finishRefresh(1000);
                ToastUtil.showToast(mContext, message);
            }
        });
    }

    /**
     * 获取订单记录
     */
    public void getTradeRecordList() {
        mAppAction.getHistoryOrderList(mPageIndex, new ActionCallbackListener<List<OrderInfoBean>>() {
            @Override
            public void onSuccess(List<OrderInfoBean> data) {
                refresh_layout.finishRefresh(1000);
                refresh_layout.finishLoadMore(1000);

                if (mPageIndex == 1) {
                    mSellOrderList = data;
                } else {
                    mSellOrderList.addAll(data);
                }
                if (data.size() >= 10) {
                    refresh_layout.setEnableLoadMore(true);
                } else {
                    refresh_layout.setEnableLoadMore(false);
                }
                if (mPageIndex == 1 && mSellOrderList.size() == 0) {
                    showEmptyView();
                } else {
                    updateRecord(mSellOrderList, true);
                    rv_list.setVisibility(View.VISIBLE);
                    tv_empty.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                refresh_layout.finishRefresh(1000);
                refresh_layout.finishLoadMore(1000);
                ToastUtil.showToast(mContext, message);
            }
        });
    }

    private void updateRecord(final List<OrderInfoBean> recordList, final boolean isInit) {
        if (myApplication.getAllGoodMap() == null) return;
        for (OrderInfoBean orderGroup : recordList) {
            orderGroup.multiple = myApplication.getAllGoodMap().get(orderGroup.pro_code).multiple;
        }
        if (isInit) {
            mRecordRVAdapter.setData(mSellOrderList);
        } else {
            mRecordRVAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 设置组别标题
     * @param list
     * @return
     */
    private List<OrderInfoGroupBean> generateOrderGroupList(List<OrderInfoBean> list) {
        Map<String, List<OrderInfoBean>> map = new LinkedHashMap<>();
        for (OrderInfoBean order : list) {
            List<OrderInfoBean> itemList = map.get(order.pro_code);
            if (itemList == null) {
                itemList = new ArrayList<>();
                map.put(order.pro_code, itemList);
            }
            itemList.add(order);
        }
        List<OrderInfoGroupBean> groupList = new ArrayList<>();
        for (String key : map.keySet()) {
            OrderInfoGroupBean groupBean = new OrderInfoGroupBean(key, map.get(key));
            groupList.add(groupBean);
        }
        return groupList;
    }

    /**
     * 设置订单金额展示
     */
    private void setOrderMoney() {
        orderMoney = 0;
        for (OrderInfoGroupBean orderGroup : mOrderInfoGroupList) {
            for (OrderInfoBean child : orderGroup.getChild()) {
                double unit_price = 0;
                if (child.use_ticket != 1) {
                    unit_price = ArithUtil.mul(child.unit_price, child.amount);//单价乘数量
                }
                orderMoney = ArithUtil.add(orderMoney, unit_price);
            }
        }
        if (mOrderInfoGroupList.size() > 0) {
            tv_frozen_balance.setText(FormatUtil.formatMoney(orderMoney) + "元");
        } else {
            tv_frozen_balance.setText("--");
        }

    }

    /**
     * 更新持有订单
     * @param orderGroupList
     * @param isInit
     */
    private void updateOrderList(final List<OrderInfoGroupBean> orderGroupList, final boolean isInit) {
        List<GoodsAllBean> data = myApplication.getAllList();
        totalFloatMoney = 0;
        for (OrderInfoGroupBean orderGroup : orderGroupList) {
            for (GoodsAllBean proBean : data) {
                if (orderGroup.getProCode().equals(proBean.pro_code)) {
                    double price_end_lastDay = proBean.price_end_lastday;
                    double newPrice = proBean.latest_price;
                    double rise = 0;
                    double risePer = 0;
                    if (price_end_lastDay != 0) {
                        rise = ArithUtil.sub(newPrice, price_end_lastDay);
                        risePer = ArithUtil.div(rise * 100, price_end_lastDay, 2);
                    }
                    orderGroup.setProName(proBean.pro_name);
                    orderGroup.setLatestPrice(newPrice);
                    orderGroup.setRise(rise);
                    orderGroup.setRisePercent(risePer + "%");
                    List<OrderInfoBean> childList = orderGroup.getChild();
                    for (OrderInfoBean child : childList) {
                        child.new_price = (newPrice);
                        child.pro_name = (proBean.pro_name);
                        child.multiple = proBean.multiple;
                        setProfitAndLoss(newPrice, child);
                    }
                    break;
                }
            }
        }
        if (isInit) {
            mOrderAdapter.setData(orderGroupList);
        } else {
            mOrderAdapter.notifyDataSetChanged();
        }
        if (orderGroupList.size() > 0) {
            setOrderMoney();
            setFloatMoney();
        } else {
            tv_frozen_balance.setText("--");
            tv_float_money.setText("--");
            tv_float_money.setTextColor(ContextCompat.getColor(mContext, R.color.color_black_01));
        }
    }

    private void showEmptyView() {
        rv_list.setVisibility(View.GONE);
        tv_empty.setVisibility(View.VISIBLE);
        switch (mCurrentIndex) {
            case TYPE_INDEX_ORDER:
                tv_go_trade.setVisibility(View.VISIBLE);
                tv_empty.setText("当前暂无订单");
                mOrderInfoGroupList.clear();
                tv_empty.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.iv_empty_order, 0, 0);
                break;
            case TYPE_INDEX_RECORD:
                tv_go_trade.setVisibility(View.GONE);
                tv_empty.setText("当前暂无记录");
                mSellOrderList.clear();
                tv_empty.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.iv_empty_order, 0, 0);
                break;
        }
    }

    private void setFloatMoney() {
        if (totalFloatMoney >= 0) {
            tv_float_money.setText("+" + FormatUtil.formatMoney(totalFloatMoney));
            tv_float_money.setTextColor(ContextCompat.getColor(mContext, R.color.buy_red));
        } else {
            tv_float_money.setText(FormatUtil.formatMoney(totalFloatMoney));
            tv_float_money.setTextColor(ContextCompat.getColor(mContext, R.color.buy_green));
        }
    }

    private void setProfitAndLoss(double latestPrice, OrderInfoBean order) {
        int flag = order.trade_type == 2 ? 1 : -1;
        int target = order.target_profit;
        int stop = order.stop_loss * -1;
        if (stop == 0) {
            stop = order.max_stop_loss * -1;
        }
        double diff = ArithUtil.sub(latestPrice, order.build_price) * flag;
        if (target != 0 && diff >= target) {
            diff = target;
        }
        if (diff <= stop) {
            diff = stop;
        }
        if (diff < 0 && order.use_ticket == 1) {
            diff = 0;
        }
        double singleProfit = ArithUtil.mul(diff, order.k_amount);
        double totalProfit = ArithUtil.mul(singleProfit, order.amount);
        totalProfit = ArithUtil.mul(totalProfit, order.multiple);
        order.profitAndLoss = (totalProfit);
        totalFloatMoney = ArithUtil.add(totalFloatMoney, totalProfit);
        if (mSellDialog != null && mSellDialog.isShowing() && order.order_id.equals(mCurrentOrderSellId)) {
            mSellDialog.setProfitLoss(order);
        }
    }

    @Override
    public void onClickSell(OrderInfoBean order) {
        this.mCurrentOrderSellId = order.order_id;
        mSellDialog = new OrderSellDialog(mContext, order);
        mSellDialog.setClickListener(new OrderSellDialog.ClickListener() {
            @Override
            public void onConfirm() {
                sell();
            }

            @Override
            public void onCancel() {

            }
        });
        if (!mSellDialog.isShowing()) {
            mSellDialog.show();
        }
    }

    private void sell() {
        baseActivity.loading();
        mAppAction.sellOrder(mCurrentOrderSellId, new ActionCallbackListener<Void>() {
            @Override
            public void onSuccess(Void data) {
                mOrderAdapter.remove(mCurrentOrderSellId);
                if (mOrderAdapter.getList().size() == 0) {
                    showEmptyView();
                }
                mSellDialog.dismiss();
                baseActivity.cancelLoading();
                updateOrderList(mOrderAdapter.getList(), false);
                myApplication.updateUserDetail();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                baseActivity.cancelLoading();
                ToastUtil.showToast(mContext, message);
                getNoManualOrderList();
            }
        });
    }

    @Override
    public void onClickOrderMarket(String proCode) {
        goMarketActivity(proCode);
    }

    private void goMarketActivity(final String proCode) {
        List<GoodsAllBean> allList = myApplication.getAllList();
        for (GoodsAllBean groupBean : allList) {
            if (proCode.equals(groupBean.pro_code)) {
                RouteUtil.toMarketActivity(baseActivity, groupBean.pro_code);
                break;
            }
        }
    }

    @Override
    public void onClickChangeProfitLost(OrderInfoBean order) {
        mUpdateDialog = new OrderUpdateDialog((BaseActivity) getActivity(), order);
        mUpdateDialog.setListener(new OrderUpdateDialog.EditOrderListener() {
            @Override
            public void onEditOrderSuccess() {
                refreshDataSource();
            }

            @Override
            public void onEditOrderLogoutStatus() {
                onLogoutStatus();
            }
        });
        if (!mUpdateDialog.isShowing()) {
            mUpdateDialog.show();
        }
    }

    @Override
    public void onClickGetGoods(OrderInfoBean order) {
        RouteUtil.toAddGoodsOrderActivity(baseActivity, order);
    }

    @Override
    public void onClickExplain(OrderInfoBean order) {

    }

    @Override
    public void onClickDetail(OrderInfoBean order) {
        RouteUtil.toOrderDetailActivity((BaseActivity) mContext, order, false);
    }

    @Override
    public void onClickExpand(int position) {
        OrderInfoBean bean = mSellOrderList.get(position);
        bean.isExpand = !bean.isExpand;
        mRecordRVAdapter.notifyItemChanged(position);
    }

    @Override
    public void onCLickDetail(OrderInfoBean bean) {
        RouteUtil.toOrderDetailActivity((BaseActivity) mContext, bean, true);
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {
        super.onEventComming(eventCenter);
        int event = eventCenter.getEventCode();
        switch (event) {
            case EventConstants.EVENTCODE_UPDATE_USER:
                getAccount();
                break;
            case EventConstants.EVENTCODE_UPDATE_PRO_PRICE:
                onPriceChanged();
                break;
        }
    }

    /**
     * 价格变动
     */
    public void onPriceChanged() {
        updateOrderList(mOrderAdapter.getList(), false);
    }
}
